﻿package com.phy.gsjl.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.phy.gsjl.dao.UserDAO;
import com.phy.gsjl.entity.User;
import com.phy.gsjl.service.IUserService;

/**
 * user服务层
 * 
 * @author curry
 *
 */
@Transactional
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	public UserDAO userDAO;

	// 获取日志对象
	private static Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Override
	public List<User> getAllUsers() {
		return userDAO.getAllUsers(); // 调用DAO层的查询方法
	}

	@Override
	public User getUserByName(String username) {
		logger.info("==>In UserSeviceImpl getUserByName parameter username: " + username);
		return userDAO.getUserByName(username); // 调用DAO层的查询方法
	}

	@Override
	public Integer getTotalRecords() {
		return userDAO.getTotalRecord(); // 调用DAO层的查询方法，返回总记录数
	}

	@Override
	public List<User> getUserIndistinct(String indistinct) {
		return userDAO.getUserIndistinct(indistinct); // 调用DAO层的查询方法
	}

	@Override
	public boolean updateUser(User user) {
		try {
			userDAO.updateUser(user); // 调用DAO层的更新方法
			return true; // 如果没有异常，则更新成功
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteUser(String username) {
		try {
			userDAO.deleteUser(username); // 调用DAO层的删除方法
			return true; // 如果没有异常，则删除成功
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteUserByBatch(String[] usernames) {
		try {
			userDAO.deleteUserByBatch(usernames); // 调用DAO层的删除方法
			return true; // 如果没有异常，则更新成功
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public List<User> getMessageByPage(Integer currentPage) {
		Integer totalRecord = userDAO.getTotalRecord(); // 调用DAO层的查询方法，返回总记录数
		List<User> users = userDAO.getCurrentPage(currentPage, totalRecord);
		return users;
	}

	@Override
	public boolean addUser(User user) {
		try {
			userDAO.addUser(user); //调用dao层添加用户
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public String addUsers(String path) {
		try {
			//解析excel
			List<User> users = parseExcelByPOI(path);
			if (users.size() == 0) {
				return "0";
			} else {
				//先判断用户是否存在，然后插入用户
				for (User user : users) {
					User userselect = getUserByName(user.getUsername());
					if (userselect == null) {
						userDAO.addUser(user);
					}
				}
				return "1";
			}

		} catch (EncryptedDocumentException e) {
			return "2";
		} catch (InvalidFormatException e) {
			return "2";
		} catch (IOException e) {
			e.printStackTrace();
			return "3";
		}

	}

	/**
	 * 使用poi方式解析，WorkbookFactory.create可以解析xls和xlsx
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws EncryptedDocumentException
	 */
	public List<User> parseExcelByPOI(String path) throws EncryptedDocumentException, InvalidFormatException, IOException {
		List<User> users = new ArrayList<User>();
		//WorkbookFactory方式可以解析两种格式
		InputStream inStream = new FileInputStream(path);
		Workbook workBook = WorkbookFactory.create(inStream);
		Sheet sheet = workBook.getSheetAt(0);
		Row row = sheet.getRow(0);
		String[] excellist = { "序号", "用户名", "密码", "真实姓名", "部门", "角色" };
		//循环比较表格第一个行是否格式正确
		for (int i = 0; i < row.getLastCellNum(); i++) {
			if (row.getCell(i).getStringCellValue().equals(excellist[i])) {
				if (row.getLastCellNum() == 6 && i == 5) {
					//循环取每一行的值创建User对象，放入list
					for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
						String username = sheet.getRow(j).getCell(1).getStringCellValue();
						String password = null;
						//处理密码可能为全数字的情况
						try {
							DecimalFormat df = new DecimalFormat("0");
							password = df.format(sheet.getRow(j).getCell(2).getNumericCellValue());
						} catch (Exception e) {
							password = sheet.getRow(j).getCell(2).getStringCellValue();
						}
						String realname = sheet.getRow(j).getCell(3).getStringCellValue();
						String department = sheet.getRow(j).getCell(4).getStringCellValue();
						String role = sheet.getRow(j).getCell(5).getStringCellValue();
						User user = new User();
						user.setUsername(username);
						user.setPassword(password);
						user.setRealname(realname);
						user.setDepartment(department);
						user.setRole(role);
						users.add(user);
						System.out.println(user.toString());
					}
				}
			}
		}
		return users;

	}

	/**
	 * 解析文件的方法,使用jxl方式 只能解析xls，
	 * 
	 * @param path
	 * @return
	 */
	public List<User> parseExcelByJxl(String path) {
		List<User> users = new ArrayList<User>();
		try {
			//获取表格对象
			jxl.Workbook workbook = jxl.Workbook.getWorkbook(new File(path));
			jxl.Sheet sheet = workbook.getSheet(0);
			String[] excellist = { "序号", "用户名", "密码", "真实姓名", "部门", "角色" };
			for (int i = 0; i < sheet.getColumns(); i++) {
				if (sheet.getCell(i, 0).getContents().equals(excellist[i])) {
					if (i == 5) {
						for (int row = 1; row < sheet.getRows(); row++) {
							String username = sheet.getCell(1, row).getContents();
							String password = sheet.getCell(2, row).getContents();
							String realname = sheet.getCell(3, row).getContents();
							String department = sheet.getCell(4, row).getContents();
							String role = sheet.getCell(5, row).getContents();
							User user = new User();
							user.setUsername(username);
							user.setPassword(password);
							user.setRealname(realname);
							user.setDepartment(department);
							user.setRole(role);
							users.add(user);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

}
